package com.vue3.blog.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Mr.小朱同学
 * @version 1.0.0
 * @date 2025/6/10 11:50
 * @description HTTP请求工具类
 */
public class RequestUtil2 {
    /**
     * 获取当前请求的 HttpServletRequest
     *
     * @return HttpServletRequest 对象
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            return attributes.getRequest();
        }
        return null;
    }

    /**
     * 示例方法：获取请求的 IP 地址
     *
     * @return IP 地址
     */
    public static String getClientIp() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            // 获取 X-Forwarded-For 头部，用于处理代理服务器的情况
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        }
        return "Unknown";
    }

    public static String getParam(String name) {
        HttpServletRequest request = getRequest();
        if (request != null) {
            return request.getParameter(name);
        }
        return "";
    }
}